package com.itheima.Demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class DemoSelector方法详解 {
    public static void main(String[] args) throws IOException {
        //创建对象;
        ServerSocketChannel ssc= ServerSocketChannel.open();
        //绑定端口
        ssc.bind(new InetSocketAddress(1314));
        //设置非阻塞
        ssc.configureBlocking(false);
        //创建对象
        ServerSocketChannel ssc2 = ServerSocketChannel.open();
        //绑定端口;
        ssc2.bind(new InetSocketAddress(1315));
        //设置非阻塞;
        ssc.configureBlocking(false);
        //创建对象;
        ServerSocketChannel ssc3 = ServerSocketChannel.open();
        //绑定端口;
        ssc3.bind(new InetSocketAddress(1316));
        //设置非阻塞;
        ssc3.configureBlocking(false);
        //把三个摊位交给一个Selector去管理
        //创建对象;
        Selector open = Selector.open();
        //把selector给摊位注册
        ssc.register(open, SelectionKey.OP_ACCEPT);
        ssc2.register(open,SelectionKey.OP_ACCEPT);
        ssc3.register(open,SelectionKey.OP_ACCEPT);
        while (true){
            //Selector帮多个端口去监听客户端
            open.select();
            //获取集合
            Set<SelectionKey> set = open.selectedKeys();
            System.out.println("集合中对象的个数是:"+set.size());
            ////遍历集合,获取迭代器对象;
            Iterator<SelectionKey> it = set.iterator();
            //使用迭代器遍历;
            while (it.hasNext()) {
                SelectionKey key = it.next();
                //获取channel对象,获取通道;
                SelectableChannel channel = key.channel();
                //向下转型
                ServerSocketChannel serverSocket = (ServerSocketChannel)channel;
                //获取客户端
                SocketChannel accept = serverSocket.accept();
                //创建数组;
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                //读取数据
                int read = accept.read(buffer);
                System.out.println(new String(buffer.array(),0,read));
                //迭代器删除;
                it.remove();

            }

        }
    }
}
